<template>
  <div class="app">
    <!-- 面包屑导航区域 开始 -->
    <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>轮播图管理</el-breadcrumb-item>
      <el-breadcrumb-item>查询轮播图</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航区域 开始 -->
    <el-card class="box-card">
      <!-- 头部查询按钮 与 搜索框 开始 -->
      <div class="searchTitle">
        <el-input
          class="searchBook"
          placeholder="请输入描述内容"
          style="width: 300px"
          v-model="condition.search"
          clearable
        >
        </el-input
        >
        <el-autocomplete
          class="inline-input bookList"
          v-model="bookName"
          clearable
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete>
        <el-button
          icon="el-icon-search"
          class="searchBookButton my-el-button"
          type="primary"
          @click="queryBookButton"
          >查询</el-button
        >
        <el-button
          icon="el-icon-plus"
          class="addBookButton"
          type="success"
          @click="addBookButton"
          >添加轮播图</el-button
        >
      </div>
      <!-- 头部查询按钮 与 搜索框 结束 -->
      <!-- table数据展示 开始 -->
      <el-table
        v-loading="loading"
        :fit="true"
        :data="rotationCharts"
        border
        style="width: 100%"
      >
        <el-table-column fixed type="index" width="50"> </el-table-column>
        <el-table-column prop="date" label="书籍名称" width="200">
          <template slot-scope="scope">
            <div>{{ scope.row.bookDetail[0].bookName }}</div>
          </template>
        </el-table-column>
        <el-table-column
          :show-overflow-tooltip="true"
          prop="chartDescribe"
          label="描述"
          width="200"
        >
        </el-table-column>
        <el-table-column label="图片" >
          <template slot-scope="scope">
            <img
              style="height:130px;width:250px;"
              :src="scope.row.chartUrl"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope">
            <el-dropdown @command="handleCommand">
              <el-button
              :class="scope.row.chartStatus == 1 ? 'my-el-button' : ''"
                :type="scope.row.chartStatus == 1 ? 'success' : 'danger'"
              >
                {{ scope.row.chartStatus == 1 ? '正常' : '已删除'
                }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item class="my-el-dropdown-item" :command="composeValue(scope.row, 0)"
                  >删除</el-dropdown-item
                >
                <el-dropdown-item class="my-el-dropdown-item" :command="composeValue(scope.row, 1)"
                  >恢复</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template slot-scope="scope">
            <el-button type="text" @click="handleEdit(scope.row)" size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- table数据展示 结束 -->
      <!-- 修改 与添加 开始 -->
      <el-dialog
        :title="flag == 1 ? '添加轮播图' : '修改轮播图'"
        :visible.sync="dialogFormVisible"
      >
        <el-form :model="rotationChart" ref="rotationChartForm">
          <el-form-item label="书籍" :label-width="formLabelWidth">
            <el-autocomplete
              class="inline-input "
              v-model="addBookName"
              clearable
              :fetch-suggestions="querySearch"
              placeholder="请输入书籍名称"
              @select="addOrModifyHandleSelect"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="描述" :label-width="formLabelWidth">
            <el-input
              v-model="rotationChart.chartDescribe"
              autocomplete="off"
              placeholder="请输入轮播图描述"
            ></el-input>
          </el-form-item>
          <el-form-item label="图片" :label-width="formLabelWidth">
            <el-upload
              ref="uploadImg"
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-change="changeUpload"
              :file-list="fileList"
              :on-remove="sonRemove"
              :http-request="uploadImg"
              accept="image/png, image/jpeg,image/jpg"
            >
              <img v-if="imageUrl" width="270px" height="140px" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="my-el-button-default" @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            class="my-el-button"
            @click="determineAddOrModify('rotationChartForm')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 修改与添加 结束 -->
    </el-card>
  </div>
</template>
<script>
import {
  queryRotationChart,
  modifyRotationChart,
  addRotationChart
} from '@/network/rotationChartManager'
import { bookQueryPage, uploadImg, uploadImgTrue } from '@/network/bookManager'
export default {
  data() {
    return {
      // 轮播图数组
      rotationCharts: [
        {
          bookDetail: [{ bookName: '' }]
        }
      ],
      // 轮播图详情
      rotationChart: {
        _id: '',
        chartBookId: '',
        chartDescribe: '',
        chartStatus: 1,
        chartUrl: ''
      },
      // 查询条件
      condition: {
        search: '',
        chartBookId: ''
      },
      bookList: [], // 书籍数组
      bookName: '', // 头部查询书籍名称
      addBookName: '',
      queryBookCondition: {
        search: ''
      },
      // table加载属性
      loading: false, // 加载属性
      dialogFormVisible: false, // 显示 添加 或 修改 属性
      flag: 1, // 1 添加  2 修改
      formLabelWidth: '120px',
      fileList: [],
      oldFileUid: null,
      file: null,
      imageUrl: ''
    }
  },
  methods: {
    // 查询激活后匹配
    querySearch(queryString, cb) {
      var restaurants = this.bookList
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      // 调用 callback 返回建议列表的数据

      cb(results)
    },
    // 修改按钮
    handleEdit(row) {
      this.flag = 2
      this.rotationChart = JSON.parse(JSON.stringify(row))
      this.addBookName = this.rotationChart.bookDetail[0].bookName
      this.imageUrl = this.rotationChart.chartUrl
      this.dialogFormVisible = true
    },
    // 添加轮播图按钮
    addBookButton() {
      this.flag = 1
      this.dialogFormVisible = true
    },
    // 删除按钮
    handleDelete(index, row) {
      console.log(index, row)
    },
    // 点击查询 按钮
    queryBookButton() {
      if (this.bookName == '') {
        this.condition.chartBookId = ''
      } else {
        let obj = this.bookList.find(item => {
          //遍历list的数据
          return item.value === this.bookName //筛选出匹配数据
        })
        if (obj == null) {
          return this.$message.warning('请选择正确的书籍')
        }
      }

      this.queryCarouselChart()
    },
    // 选中 书籍
    handleSelect(item) {
      this.condition.chartBookId = item._id
    },
    // 添加时 选中
    addOrModifyHandleSelect(item) {
      this.rotationChart.chartBookId = item._id
      console.info(item)
    },
    // 过滤其他字符
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        )
      }
    },
    // 处理数据
    loadAll(res) {
      this.bookList = []
      for (let rs in res) {
        let dropDownList = {}
        dropDownList.value = JSON.parse(res[rs]).bookName
        dropDownList._id = JSON.parse(res[rs])._id
        this.bookList.push(dropDownList)
      }
    },
    // 查询 轮播图
    async queryCarouselChart() {
      this.loading = true
      let res = await queryRotationChart(this.condition)
      console.info(res)
      this.rotationCharts = JSON.parse(res.resp_data).list
      this.loading = false
      console.info(this.rotationCharts)
    },
    // 修改 轮播图状态 删除 或 修改
    async handleCommand(command) {
      if (command.row.chartStatus != command.status) {
        this.$confirm('此操作将修改该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            command.row.chartStatus = command.status
            modifyRotationChart(command.row)
            this.$message.success('修改成功')
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消修改'
            })
          })
      }
    },
    // 修改 轮播图 信息
    modify(option) {
      console.info(option)
    },
    // 处理多参数
    composeValue(row, status) {
      return {
        row,
        status
      }
    },
    // 图片上传成功后的回调
    handleAvatarSuccess() {
      this.imageUrl = URL.createObjectURL(this.file.raw)
      this.$message.success('创建成功')
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    changeUpload(file, fileList) {
      this.file = file
      console.info(file)
      const isJPG = new RegExp('^image/.*$').test(file.raw.type)
      const isLt2M = file.raw.size / 1024 / 1024 < 2
      this.fileList = fileList
      if (isJPG && isLt2M) {
        this.fileList.length > 1 ? this.fileList.splice(0, 1) : ''
        this.oldFileUid = file.uid
      } else {
        this.fileList.length > 1
          ? this.fileList.splice(1, 1)
          : this.fileList.splice(0, 1)
        if (!isJPG) {
          this.$message.error('只能上传图片哦')
        } else if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
      }
      // console.info( this.imgUrl)
    },
    // 移除文件时触发
    sonRemove(file) {
      console.info(file)
    },
    // 自定义上传方法
    async uploadImg() {
      let file = this.file
      const isJPG = new RegExp('^image/.*$').test(file.raw.type)
      if (!isJPG) {
        return
      }

      const imgName =
        `rotationChart/${this.addBookName}轮播图/` +
        new Date().getTime() +
        file.name
      let res = await uploadImg(imgName)
      // 将返回的地址 处理成代理地址
      let website = res.url.substring(0, res.url.indexOf('com') + 3)
      let trueUrl = res.url.replace(website, '/img')
      // 将数据封装成 formData
      const formData = new FormData()
      formData.append('Signature', res.authorization)
      formData.append('key', imgName)
      formData.append('x-cos-security-token', res.token)
      formData.append('x-cos-meta-fileid', res.cos_file_id)
      formData.append('file', file.raw)
      uploadImgTrue(trueUrl, formData) // 最后一步上传图片
      const imgUrl = `https://7a68-zhuma-mbnti-1302831863.tcb.qcloud.la/${imgName}`
      this.rotationChart.chartUrl = imgUrl // 将图片路径 存入表单对象中

      console.info(imgUrl)
    },
    // 图片上传 前的回调
    beforeAvatarUpload(file) {
      console.log(file)
      if (this.addBookName == '') {
        this.$message.warning('请先选择书籍')
        return false
      }
    },
    // 确定修改 或者 添加
    async determineAddOrModify() {
      // 添加
      if (this.flag == 1) {
        console.info(this.rotationChart)
        console.info(this.addBookName)
        let obj = null
        console.info(this.bookList)
        obj = this.bookList.find(item => {
          //遍历list的数据
          return item.value === this.addBookName //筛选出匹配数据
        })
        if (obj == null) return this.$message.warning('请选择正确在的书籍')

        if (this.rotationChart.chartDescribe == '')
          return this.$message.warning('请填写轮播图描述')

        if (this.file == null)
          return this.$message.warning('请选择需要上传的图片')
        let res = await addRotationChart(this.rotationChart)
        console.info(this.rotationChart)
        console.info(res)
        this.reset()
        this.$message.success('添加成功')
        this.queryCarouselChart()
        return
      }
            // 修改
      this.$confirm('此操作将永久修改该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let res = this.rotationCharts.filter(item => { return item._id==  this.rotationChart._id});
          if(res!=null){
             res.chartUrl=  this.rotationChart.chartUrl
          }
          modifyRotationChart(this.rotationChart)
          this.$message.success('修改成功')
          this.reset()
          this.queryCarouselChart()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          })
        })

    },
    // 重置
    reset() {
      this.imageUrl = ''
      this.rotationChart.chartDescribe = ''
      this.rotationChart.chartBookId = ''
      this.addBookName = ''
      this.dialogFormVisible = false
    }
  },
  async mounted() {
    this.queryCarouselChart()
    let bookListRes = await bookQueryPage({
      page: 1,
      size: 1000
    })
    this.loadAll(bookListRes.data)
    console.info(bookListRes)
  }
}
</script>
<style lang="less" scoped>
.searchTitle {
  margin-bottom: 30px;
}
.bookList {
  margin-left: 20px;
}
.addBookButton {
  float: right;
}
.addBookButton::after {
  content: '';
  display: inline-block;
  clear: both;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #fd7c27;
}
.searchBookButton{
  margin-left: 20px;
}
</style>
